package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((menu1,menu2)->(menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort()))
                .collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO: 1. 检查是否被引用
        baseMapper.deleteBatchIds(asList);
    }

    @Cacheable(value={"category"},key="#root.methodName")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        System.out.println("查询了数据库...");
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);
        // 查出所有1级分类
        List<CategoryEntity> level1Categorys = getParentCid(selectList, 0L);
        // 封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys
                .stream()
                .collect(Collectors.toMap(
                        k -> k.getCatId().toString(),
                        v -> {
                            // 查询一级分类的所有二级分类
                            List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getCatId());
                            // 封装以上结果
                            List<Catelog2Vo> catelog2Vos = null;
                            if (categoryEntities != null) {
                                catelog2Vos = categoryEntities
                                        .stream()
                                        .map(l2 -> {
                                            Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                                            // 封装三级分类
                                            List<CategoryEntity> level3Catelog = getParentCid(selectList, l2.getCatId());
                                            if (level3Catelog != null) {
                                                List<Catelog2Vo.Catelog3Vo> collect = level3Catelog
                                                        .stream()
                                                        .map(l3 -> new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName()))
                                                        .collect(Collectors.toList());
                                                catelog2Vo.setCatalog3List(collect);
                                            }
                                            return catelog2Vo;
                                        })
                                        .collect(Collectors.toList());
                            }
                            return catelog2Vos;
                        }));
        return parent_cid;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJson2() {
        // 1.查询缓存中是否有数据
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            // 缓存中没有数据，查询数据库
            System.out.println("缓存不命中...查询数据库");
            Map<String, List<Catelog2Vo>> catalogJsonFromDB = getCatalogJsonFromDB();
            return catalogJsonFromDB;
        }
        System.out.println("缓存命中...直接返回...");
        // 将redis中的串转为对象并返回
        return JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
    }

    private Map<String, List<Catelog2Vo>> getCatalogJsonFromDB() {
        /*优化：将数据库的多次查询精简*/
        System.out.println("查询了数据库...");
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);
        // 查出所有1级分类
        List<CategoryEntity> level1Categorys = getParentCid(selectList, 0L);
        // 封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Categorys
                .stream()
                .collect(Collectors.toMap(
                        k -> k.getCatId().toString(),
                        v -> {
                            // 查询一级分类的所有二级分类
                            List<CategoryEntity> categoryEntities = getParentCid(selectList, v.getCatId());
                            // 封装以上结果
                            List<Catelog2Vo> catelog2Vos = null;
                            if (categoryEntities != null) {
                                catelog2Vos = categoryEntities
                                        .stream()
                                        .map(l2 -> {
                                            Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                                            // 封装三级分类
                                            List<CategoryEntity> level3Catelog = getParentCid(selectList, l2.getCatId());
                                            if (level3Catelog != null) {
                                                List<Catelog2Vo.Catelog3Vo> collect = level3Catelog
                                                        .stream()
                                                        .map(l3 -> new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName()))
                                                        .collect(Collectors.toList());
                                                catelog2Vo.setCatalog3List(collect);
                                            }
                                            return catelog2Vo;
                                        })
                                        .collect(Collectors.toList());
                            }
                            return catelog2Vos;
                        }));
        stringRedisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(parent_cid), 1, TimeUnit.DAYS);
        return parent_cid;
    }

    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId()).map(categoryEntity -> {
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1,menu2)->(menu1.getSort()==null?0:menu1.getSort())-(menu2.getSort()==null?0:menu2.getSort())).collect(Collectors.toList());
        return children;
    }
    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList, Long parentCid) {
        return selectList.stream().filter(item -> Objects.equals(item.getParentCid(), parentCid)).collect(Collectors.toList());
//        return this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
    }
}